package cn.stylefeng.guns.sys.modular.sms.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author funcong
 * @create 2021/5/4
 */
@RestController
@RequestMapping("/api")
public class CaptchaController {


    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping(value = "/captcha", method = RequestMethod.POST)
    public void appCaptcha(HttpServletResponse response,
                          @RequestParam("key") String key) {
        //定义图形验证码的长和宽
        ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(250, 100, 4, 4);
        //图形验证码写出，可以写出到文件，也可以写出到流
        response.setContentType("image/png");
        ServletOutputStream outputStream;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        captcha.write(outputStream);
        redisTemplate.opsForValue().set(key, captcha.getCode(), 30, TimeUnit.MINUTES);
    }
}
